package com.example.ffepeg.service;

import com.example.ffepeg.ffeAdder.QpsLimitedThreadPool;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


@Service
public class QLServiceImpl {
    public static final BlockingQueue<Map<String,Object>> mapQueue = new LinkedBlockingQueue<>(5);

    public String addQueue(String json) {
        String id = UUID.randomUUID().toString();
        Map<String,Object> map = new HashMap<>();
        map.put(id,json);
        if (!(mapQueue.offer(map))){
            throw new RuntimeException("访问人数太多了,请稍后再访问");
        }
        executeAsync(); //异步方法
        return id;
    }


    @Async
    public void executeAsync(){
        QpsLimitedThreadPool pool = new QpsLimitedThreadPool(2); // 设置QPS为2
        while (!mapQueue.isEmpty()) {
            try {
                Map<String, Object> currentMap = mapQueue.take();
                for (Map.Entry<String, Object> entry : currentMap.entrySet()) {
                    String requestId = entry.getKey();
                    String json = String.valueOf(entry.getValue());
                    pool.execute(() -> {
                        try {
                            Thread.sleep(30000);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    });
                }
                pool.shutdown();
            } catch (Exception e) {
                pool.shutdown();
                Thread.currentThread().interrupt();
                System.out.println("等待任务完成中被中断: "+ e);
                break;
            }
        }
    }

    private static final QpsLimitedThreadPool pool = new QpsLimitedThreadPool(1); // 设置QPS为2
    public static void createPool() {
        try {
            for (int i = 0; i < 3; i++) {
                int index = i;
                pool.execute(() -> {
                    System.out.println("Executing " + index + " at " + System.currentTimeMillis());
                    try {
                        Thread.sleep(10000); // 模拟耗时操作
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                });
            }
        } catch (Exception e){
            System.out.println("失败: "+ e);
            pool.shutdown();
        } finally {
            pool.shutdown();
        }
    }

    public static void main(String[] args) {
        createPool();
    }

}
